package com.ultrapower.controller;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.ultrapower.commons.base.BaseController;
import com.ultrapower.commons.result.PageInfo;
import com.ultrapower.commons.utils.StringUtils;
import com.ultrapower.model.LlBlackListDm;
import com.ultrapower.service.IBlackListService;
import com.ultrapower.service.IUserService;
import com.ultrapower.task.UploadBlackList;

/**
 * @description：黑名单
 * @author：龚伟
 * @date：2018/08/21
 */
@Controller
@RequestMapping("/blackList")
public class BlackListController extends BaseController{
	
	@Autowired
    private IBlackListService blackListService;
	@Autowired
    private IUserService userService;
	
	/**
     * 黑名单首页
     *
     * @return
     */
    @GetMapping("/list")
    public String manager() {
        return "admin/blackList/blackList";
    }
    
    /**
     * 用户管理列表
     *
     * @param userVo
     * @param page
     * @param rows
     * @param sort
     * @param order
     * @return
     */
    @PostMapping("/dataGrid")
    @ResponseBody
    public Object dataGrid(LlBlackListDm black, Integer page, Integer limit, String sort, String order) {
    	sort = "stat_date";
    	order = "asc";
        PageInfo pageInfo = new PageInfo(page, limit, sort, order);
        Map<String, Object> condition = new HashMap<String, Object>();

        if (StringUtils.isNotBlank(black.getPhone_no())) {
            condition.put("phone_no", black.getPhone_no());
        }
        /*
         * 是否发送短信
         * 1：是   2：否
         */
        if (black.getSend_message() == 1) {
            condition.put("send_message", 0);
        }else if (black.getSend_message() == 2){
        	 condition.put("send_message", 1);
        }
        /*
         * 用户是否回复
         * 1：是   2：否
         */
        if (black.getIs_answer() == 1) {
            condition.put("is_answer", 0);
        }else if (black.getIs_answer() == 2){
        	condition.put("is_answer", 1);
        }
        pageInfo.setCondition(condition);
        blackListService.selectDataGrid(pageInfo);
        return pageInfo;
    }
    /**
     * 文件上传
     * @param request
     * @param file
     * @return
     */
    @PostMapping("/fileUpload")
    @ResponseBody
    public String uploadFile(HttpServletRequest request,MultipartFile file){
    	JSONObject json = new JSONObject();
    	JSONObject jsonData = new JSONObject();
        try {
        	//文件上传路径
        	request.setCharacterEncoding("UTF-8");
            String path = request.getServletContext().getRealPath("/");
			String filename = file.getOriginalFilename();
			//写入本地磁盘
			InputStream is = file.getInputStream();
			byte[] bs = new byte[1024];
			int len;
			path = request.getSession().getServletContext().getRealPath("uploadfileDir"); //获取服务器指定文件存取路径
			//path = "D:/tmpfile/";
			//path = "D:/tmp/";
			File tmpfile = new File(path);
			if(!tmpfile.exists()){
				tmpfile.mkdir();
			}
			OutputStream os = new FileOutputStream(new File(path,filename));
			while ((len = is.read(bs)) != -1) {
				os.write(bs, 0, len);
			}
			List<Map<String, String>> mapData = new UploadBlackList().doUpload(path+"/"+filename);
			
//			TSysuser user = userService.selectById(getUserId());
			
			//这里批量添加
			Map<String, String> rowData = null;
			for (int i = 0; i < mapData.size(); i++) {
				LlBlackListDm bl = new LlBlackListDm();
				rowData = mapData.get(i);
				String phoneNo = rowData.get("电话号码");
				if(phoneNo.indexOf("E")>-1){
					BigDecimal bd = new BigDecimal(phoneNo);
					bl.setPhone_no(bd.toPlainString());
				}else{
					bl.setPhone_no(rowData.get("电话号码"));
				}
				String idCard = rowData.get("身份证");
				bl.setCert_id(idCard);
				String imei = rowData.get("IMEI");
				bl.setImei_14(imei);
				bl.setData_source(1);//用户导入
				bl.setSend_message(1);//是否发送短信   --默认值1 	未发送
				bl.setIs_answer(1);//是否回复	--默认值1 	未回复
				bl.setAnswer_state(-1); //回复状态 		--默认值-1
				bl.setStat_date(new SimpleDateFormat("yyyyMMdd").format(new Date()));
//				bl.setName(user.getName());
//				bl.setTime(new Date(System.currentTimeMillis()));
//				bl.setType(Integer.parseInt(rowData.get("类型(诈骗号码:0;疑似诈骗号码:1)")));
				blackListService.insert(bl);
			}
	    	json.put("code", 0);
	    	json.put("msg", "");
	    	jsonData.put("src", filename);
	    	json.put("data", jsonData);
			os.close();
			is.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return json.toString();
    }
    
    /**
     * 获取场景总数
     *
     * @return
     */
    @GetMapping("/blackListCount")
    @ResponseBody
    public int blackListCount() {
        int count = blackListService.selectListCount();
        return count;
    }
}
